import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  List, 
  Avatar, 
  Tag, 
  Button, 
  Input, 
  Select, 
  Space, 
  Pagination,
  Empty,
  Spin,
  Tabs,
  Image,
  Row,
  Col,
  Badge
} from 'antd';
import { 
  ShoppingOutlined, 
  PlusOutlined, 
  SearchOutlined,
  EyeOutlined,
  HeartOutlined,
  MessageOutlined,
  ClockCircleOutlined,
  UserOutlined,
  DollarOutlined
} from '@ant-design/icons';
import { PRODUCT_STATUS } from '../../constants';
import { Product } from '../../types';
import './Trade.scss';

const { Search } = Input;
const { Option } = Select;
const { TabPane } = Tabs;

const Trade: React.FC = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [products, setProducts] = useState<Product[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [sortBy, setSortBy] = useState('latest');
  const [activeTab, setActiveTab] = useState('all');

  // 模拟交易数据
  const mockProducts: Product[] = [
    {
      id: '1',
      title: 'MacBook Pro 2019 13寸',
      description: '配置：i5处理器，8GB内存，256GB固态硬盘，成色9成新，无磕碰',
      price: 6500,
      images: ['https://picsum.photos/300/200?random=1'],
      seller: { id: '1', username: '张三', email: 'zhangsan@example.com', role: 'student' },
      category: '电子产品',
      status: 'available',
      tags: ['9成新', '无磕碰'],
      createdAt: '2024-01-15T10:00:00Z',
      updatedAt: '2024-01-15T10:00:00Z',
    },
    {
      id: '2',
      title: '机械键盘 Cherry MX',
      description: '青轴机械键盘，RGB背光，适合编程和游戏，使用半年',
      price: 299,
      images: ['https://picsum.photos/300/200?random=2'],
      seller: { id: '2', username: '李四', email: 'lisi@example.com', role: 'student' },
      category: '电子产品',
      status: 'available',
      tags: ['8成新', '在保'],
      createdAt: '2024-01-15T09:30:00Z',
      updatedAt: '2024-01-15T09:30:00Z',
    },
    {
      id: '3',
      title: '二手自行车',
      description: '山地自行车，7成新，适合校园代步，刹车灵敏',
      price: 180,
      images: ['https://picsum.photos/300/200?random=3'],
      seller: { id: '3', username: '王五', email: 'wangwu@example.com', role: 'student' },
      category: '生活用品',
      status: 'available',
      tags: ['7成新', '功能正常'],
      createdAt: '2024-01-15T08:45:00Z',
      updatedAt: '2024-01-15T08:45:00Z',
    },
    {
      id: '4',
      title: '编程书籍合集',
      description: '《算法导论》《数据结构与算法》《设计模式》等经典编程书籍',
      price: 120,
      images: ['https://picsum.photos/300/200?random=4'],
      seller: { id: '4', username: '赵六', email: 'zhaoliu@example.com', role: 'student' },
      category: '图书资料',
      status: 'sold',
      tags: ['品相好', '无划痕'],
      createdAt: '2024-01-14T16:30:00Z',
      updatedAt: '2024-01-14T16:30:00Z',
    },
    {
      id: '5',
      title: '宿舍用品套装',
      description: '台灯、收纳盒、床上桌等宿舍生活用品，打包出售',
      price: 80,
      images: ['https://picsum.photos/300/200?random=5'],
      seller: { id: '5', username: '孙七', email: 'sunqi@example.com', role: 'student' },
      category: '生活用品',
      status: 'reserved',
      tags: ['7成新', '打包优惠'],
      createdAt: '2024-01-14T14:20:00Z',
      updatedAt: '2024-01-14T14:20:00Z',
    },
    {
      id: '6',
      title: 'iPad Air 4',
      description: '64GB WiFi版，银色，成色95新，配件齐全',
      price: 2800,
      images: ['https://picsum.photos/300/200?random=6'],
      seller: { id: '6', username: '周八', email: 'zhouba@example.com', role: 'student' },
      category: '电子产品',
      status: 'available',
      tags: ['95新', '在保', '配件齐全'],
      createdAt: '2024-01-14T11:15:00Z',
      updatedAt: '2024-01-14T11:15:00Z',
    },
  ];

  const subCategories = [
    { key: 'all', label: '全部商品' },
    { key: 'electronics', label: '电子产品' },
    { key: 'daily', label: '生活用品' },
    { key: 'books', label: '图书资料' },
  ];

  useEffect(() => {
    loadProducts();
  }, [currentPage, searchKeyword, sortBy, activeTab]);

  const loadProducts = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 500));
      
      let filteredProducts = mockProducts;
      
      // 按子分类过滤
      if (activeTab !== 'all') {
        filteredProducts = mockProducts.filter(product => {
          switch (activeTab) {
            case 'electronics':
              return product.category === '电子产品';
            case 'daily':
              return product.category === '生活用品';
            case 'books':
              return product.category === '图书资料';
            default:
              return true;
          }
        });
      }
      
      // 按关键词搜索
      if (searchKeyword) {
        filteredProducts = filteredProducts.filter(product => 
          product.title.includes(searchKeyword) || 
          product.description.includes(searchKeyword) ||
          product.category.includes(searchKeyword)
        );
      }
      
      // 排序
      filteredProducts.sort((a, b) => {
        switch (sortBy) {
          case 'latest':
            return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
          case 'price-low':
            return a.price - b.price;
          case 'price-high':
            return b.price - a.price;
          case 'popular':
            return b.price - a.price; // 这里可以用其他指标
          default:
            return 0;
        }
      });
      
      setProducts(filteredProducts);
      setTotal(filteredProducts.length);
    } catch (error) {
      console.error('加载商品失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleProductClick = (productId: string) => {
    navigate(`/posts/trade/${productId}`);
  };

  const handleContactSeller = (productId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    console.log('联系卖家:', productId);
  };

  const handleAddToFavorites = (productId: string, e: React.MouseEvent) => {
    e.stopPropagation();
    console.log('收藏商品:', productId);
  };

  const handleSearch = (value: string) => {
    setSearchKeyword(value);
    setCurrentPage(1);
  };

  const handleSortChange = (value: string) => {
    setSortBy(value);
    setCurrentPage(1);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    setCurrentPage(1);
  };

  const getStatusColor = (status: string) => {
    const colors = {
      available: 'green',
      sold: 'red',
      reserved: 'orange',
    };
    return colors[status as keyof typeof colors] || 'default';
  };

  const getCategoryColor = (category: string) => {
    const colors = {
      '电子产品': 'blue',
      '生活用品': 'green',
      '图书资料': 'orange',
    };
    return colors[category as keyof typeof colors] || 'default';
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      return '今天';
    } else if (days === 1) {
      return '昨天';
    } else if (days < 7) {
      return `${days}天前`;
    } else {
      return date.toLocaleDateString();
    }
  };

  return (
    <div className="trade-page">
      <div className="page-header">
        <div className="header-left">
          <h1>交易区</h1>
          <p>二手交易，物尽其用，校园生活</p>
        </div>
      </div>

      {/* 子分类标签 */}
      <Card className="category-card">
        <Tabs 
          activeKey={activeTab} 
          onChange={handleTabChange}
          items={subCategories.map(cat => ({
            key: cat.key,
            label: cat.label,
          }))}
        />
      </Card>

      {/* 筛选和搜索 */}
      <Card className="filter-card">
        <div className="filter-content">
          <Space size="middle" wrap>
            <Search
              placeholder="搜索商品..."
              allowClear
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            <Select
              value={sortBy}
              onChange={handleSortChange}
              style={{ width: 120 }}
            >
              <Option value="latest">最新发布</Option>
              <Option value="price-low">价格从低到高</Option>
              <Option value="price-high">价格从高到低</Option>
            </Select>
          </Space>
        </div>
      </Card>

      {/* 商品网格 */}
      <Card className="products-card">
        <Spin spinning={loading}>
          {products.length > 0 ? (
            <>
              <Row gutter={[16, 16]}>
                {products.map((product) => (
                  <Col xs={24} sm={12} lg={8} xl={6} key={product.id}>
                    <Card
                      hoverable
                      className="product-card"
                      cover={
                        <div className="product-cover">
                          <img
                            alt={product.title}
                            src={product.images[0]}
                            style={{ height: 200, objectFit: 'cover', width: '100%' }}
                          />
                          <Badge 
                            status={product.status === 'available' ? 'success' : 
                                   product.status === 'sold' ? 'error' : 'warning'}
                            text={PRODUCT_STATUS[product.status as keyof typeof PRODUCT_STATUS]}
                            className="product-status-badge"
                          />
                        </div>
                      }
                      onClick={() => handleProductClick(product.id)}
                    >
                      <div className="product-info">
                        <div className="product-header">
                          <h3 className="product-title">{product.title}</h3>
                          <Tag color={getCategoryColor(product.category)}>
                            {product.category}
                          </Tag>
                        </div>
                        
                        <div className="product-tags">
                          {product.tags && product.tags.map((tag, index) => (
                            <Tag key={index} color="blue">{tag}</Tag>
                          ))}
                        </div>
                        
                        <p className="product-description">{product.description}</p>
                        
                        <div className="product-footer">
                          <div className="product-price">
                            <span className="price">¥{product.price}</span>
                          </div>
                          
                          <div className="product-meta-info">
                            <span className="seller">
                              <UserOutlined /> {product.seller.username}
                            </span>
                            <span className="time">
                              <ClockCircleOutlined /> {formatDate(product.createdAt)}
                            </span>
                          </div>
                        </div>
                        
                        <div className="product-actions">
                          <Button 
                            type="text" 
                            size="small"
                            icon={<HeartOutlined />}
                            onClick={(e) => handleAddToFavorites(product.id, e)}
                          >
                            收藏
                          </Button>
                          {product.status === 'available' && (
                            <Button 
                              type="primary" 
                              size="small"
                              onClick={(e) => handleContactSeller(product.id, e)}
                            >
                              联系卖家
                            </Button>
                          )}
                        </div>
                      </div>
                    </Card>
                  </Col>
                ))}
              </Row>
              
              {total > 0 && (
                <div className="pagination-wrapper">
                  <Pagination
                    current={currentPage}
                    total={total}
                    pageSize={12}
                    onChange={setCurrentPage}
                    showSizeChanger={false}
                    showTotal={(total, range) => 
                      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
                    }
                  />
                </div>
              )}
            </>
          ) : (
            <Empty 
              description="暂无商品"
              image={Empty.PRESENTED_IMAGE_SIMPLE}
            />
          )}
        </Spin>
      </Card>
    </div>
  );
};

export default Trade;
